#include "customproxymodel.h"
#include <QFileInfo>
#include "../core/codeprocessor.h"

CustomProxyModel::CustomProxyModel(QObject *parent)
    : QSortFilterProxyModel(parent)
{
}

void CustomProxyModel::setSelectedLanguages(const QStringList &languages)
{
    if (m_selectedLanguages != languages) {
        m_selectedLanguages = languages;
        
        // 更新扩展名缓存
        m_extensionCache.clear();
        for (const QString &lang : languages) {
            if (lang != "全部") {
                m_extensionCache[lang] = CodeProcessor::getExtensionsForLanguage(lang);
            }
        }
        
        invalidateFilter();
    }
}

void CustomProxyModel::setSizeFilter(const QString &sizeFilter)
{
    m_sizeFilter = sizeFilter;
    invalidateFilter();
}

bool CustomProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
{
    static QModelIndex lastParent;
    static int lastRow = -1;
    
    // 避免重复过滤相同的项
    if (sourceParent == lastParent && sourceRow == lastRow) {
        return true;
    }
    
    lastParent = sourceParent;
    lastRow = sourceRow;
    
    QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
    QString filePath = fileModel()->filePath(index);
    QFileInfo fileInfo(filePath);
    
    // 如果是目录，则接受它以便能够遍历其内容
    if (fileInfo.isDir()) {
        return true;
    }
    
    // 检查文件是否匹配语言和大小过滤器
    return matchesLanguageFilter(fileInfo) && matchesSizeFilter(fileInfo);
}

bool CustomProxyModel::matchesLanguageFilter(const QFileInfo &fileInfo) const
{
    // 如果没有选择语言或选择了"全部"，显示所有文件
    if (m_selectedLanguages.isEmpty() || m_selectedLanguages.contains("全部")) {
        return true;
    }
    
    QString suffix = "." + fileInfo.suffix().toLower();
    
    // 使用缓存的扩展名列表进行检查
    for (const QString &language : m_selectedLanguages) {
        if (m_extensionCache.value(language).contains(suffix)) {
            return true;
        }
    }
    
    return false;
}

bool CustomProxyModel::matchesSizeFilter(const QFileInfo &fileInfo) const
{
    if (m_sizeFilter.isEmpty() || m_sizeFilter == "全部") {
        return true;
    }
    
    qint64 fileSize = fileInfo.size();
    
    if (m_sizeFilter == "< 1MB") {
        return fileSize < 1024 * 1024;
    } else if (m_sizeFilter == "1MB - 10MB") {
        return fileSize >= 1024 * 1024 && fileSize <= 10 * 1024 * 1024;
    } else if (m_sizeFilter == "> 10MB") {
        return fileSize > 10 * 1024 * 1024;
    }
    
    return true;
}

QFileSystemModel *CustomProxyModel::fileModel() const
{
    return qobject_cast<QFileSystemModel*>(sourceModel());
} 